package cn.wizzer.app.web.commons.ext.websocket.action.msg.attendant;

import cn.wizzer.app.user.modules.models.UserChatMsg;
import cn.wizzer.app.user.modules.models.enums.MsgStatusEnum;
import cn.wizzer.app.user.modules.models.vo.ChatUserVO;
import cn.wizzer.app.user.modules.services.UserChatMsgService;
import cn.wizzer.app.web.commons.ext.websocket.filter.TokenFilter;
import cn.wizzer.app.web.commons.ext.websocket.main.action.BaseNettyAction;
import cn.wizzer.app.web.commons.ext.websocket.main.action.NettyAction;
import cn.wizzer.app.web.commons.ext.websocket.main.base.NettyCache;
import cn.wizzer.app.web.commons.ext.websocket.main.result.ChatResult;
import cn.wizzer.app.web.commons.utils.NettyMsgUtil;
import cn.wizzer.framework.base.Result;
import cn.wizzer.framework.util.param.Param;
import cn.wizzer.framework.util.param.Param4Map;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

@IocBean
@NettyAction(uri = "/attendant/read",filters = {TokenFilter.class})
public class ReadAction extends BaseNettyAction {

    @Inject
    @Reference
    private UserChatMsgService chatMsgService;

    @Override
    public Result action(Channel income, @Param4Map(fields = {@Param(name = "ids",required = true)}) JSONObject params) {
        ChatUserVO self = NettyCache.globalGet(params.get("appid"));

        JSONArray ids = params.getJSONArray("ids");

        int update = chatMsgService.update(Chain.make("status", MsgStatusEnum.READ), Cnd.where("id", "in", ids));

        for (Object id : ids) {
            UserChatMsg fetch = chatMsgService.fetch(id.toString());
            ChatUserVO from = NettyCache.globalGet(fetch.getUserId());
            NettyMsgUtil.send(from.getChannel(), ChatResult.MessageTypeEnum.ACTION, ChatResult.ActionEnum.READ,self,fetch.getId());
        }

        return Result.success(update);
    }

}
